package com.wei.web.middleware.httpfilter.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Chuanding.Si
 * @date 2021/9/2 3:03 PM
 */
@Slf4j
public class ZvaCorsConfiguration extends CorsConfiguration {

    @Nullable
    @Override
    public String checkOrigin(@Nullable String requestOrigin) {

        List<String> allowedOrigins = this.getAllowedOrigins();
        log.debug("allowedOrigins: {}", allowedOrigins);

        if (!StringUtils.hasText(requestOrigin)) {
            return null;
        }
        if (ObjectUtils.isEmpty(allowedOrigins)) {
            return null;
        }

        if (allowedOrigins.contains(ALL)) {
            if (this.getAllowCredentials() != Boolean.TRUE) {
                return ALL;
            } else {
                return requestOrigin;
            }
        }

        for (String allowedOrigin : allowedOrigins) {
            if (allowedOrigin.startsWith(CorsUtil.CORS_PATTERN_PREFIX)) {
                allowedOrigin = allowedOrigin.replace(CorsUtil.CORS_PATTERN_PREFIX, "");
                if (Pattern.matches(allowedOrigin, requestOrigin)) {
                    return requestOrigin;
                }
            } else {
                if (requestOrigin.equalsIgnoreCase(allowedOrigin)) {
                    return requestOrigin;
                }
            }
        }

        return null;
    }

    @Override
    public ZvaCorsConfiguration applyPermitDefaultValues() {
        super.applyPermitDefaultValues();
        return this;
    }
}
